/*
 * occupation_mgr.h
 *
 *  Created on: Nov 13, 2013
 *      Author: killerg
 */

#ifndef OCCUPATION_MGR_H_
#define OCCUPATION_MGR_H_

#include "player_data.h"

struct position_t {
    player_t* occupant;
    time_t finish;
    position_t():occupant(NULL), finish(-1){}
};

struct region_t {

    const tagProtoBossLevel* proto;
    position_t pos[OccupationPosNum];

    // player 》= 0 找该玩家的
    position_t* find_pos(int64_t playerid) {
        if (playerid < 0)
            return NULL;

        for (int i=0; i<OccupationPosNum; ++i) {
            if (NULL != pos[i].occupant && pos[i].occupant->id == playerid)
                return pos+i;
        }

        return NULL;
    }
};

struct occupation_mgr {
    occupation_mgr() {
        _inited = false;
        save_timer = 0.0f;
        chged = false;
    }

    bool init();
    bool init(const Json::Value &json);
    void save(Json::Value &json);
    void update();
    void destroy();

    void on_logon(player_t* player);
    player_t* finish_occupy(int64_t playerid, const char* hisname = NULL);

    void send_occuptionstatus(client_session_t* sess, int32_t levelid);

    region_t* fetch_region(int32_t mapid) {
        const tagProtoBossLevel* proto = MAProto(BossLevel, mapid);
        if (NULL == proto)
            return NULL;

        auto region = regions.get(mapid);
        if (NULL == region) {
            region = new region_t;
            region->proto = proto;
            regions.set(mapid, region);
        }

        return region;
    }

    std::unordered_map<int64_t, int32_t> player_occupied;
    bool chged;
    bool saving;

private:
    ptr_map<int32_t, region_t*> regions;
    double save_timer;
    bool _inited;
};

#endif /* OCCUPATION_MGR_H_ */
